package com.zc.exception;

import com.alibaba.fastjson.JSON;
import com.zc.base.ResponseResult;
import com.zc.utils.WebUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @description: 认证失败：它会封装AuthenticationException，然后调用AuthenticationEntryPoint的commence方法处理
 * @author: cong
 * @create: 2024/8/7
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        ResponseResult<Object> responseResult = new ResponseResult<>(HttpStatus.UNAUTHORIZED.value(), "认证失败，请重新登录", null);
        String jsonString = JSON.toJSONString(responseResult);
        WebUtil.renderString(response, jsonString);
    }
}
